package com.wys.spring;

import com.wys.api.exception.BizException;
import com.wys.spring.log.RequestLog;
import okhttp3.Interceptor;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketException;


public class OKHttp3Interceptor implements Interceptor {

    private static final Logger logger = LoggerFactory.getLogger(OKHttp3Interceptor.class);

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) {
        Response response = null;
        long startTime = System.currentTimeMillis();
        try {
            logger.warn("拦截OpenFeign URI:{}", chain.request());
            response = chain.proceed(chain.request());
        }catch ( SocketException n){
            logger.error("socket请求异常:", n);
            throw new BizException("远程请求异常");
        }catch (Exception e) {
            logger.error("okhttp拦截器异常:", e);
            throw new BizException("业务请求异常");
        } finally {
            long endTime = System.currentTimeMillis() - startTime;
            assert response != null;
            logger.warn("拦截OpenFeign Response:{} ,总耗时:{}ms", response, endTime);
        }
        return response;
    }
}
